{% extends 'base.html' %}

{% block title %}编辑校区 - {{ campus.name }} - 乒乓球培训管理系统{% endblock %}

{% block page_title %}编辑校区{% endblock %}

{% block extra_css %}
<style>
    .form-card {
        background: white;
        border-radius: 15px;
        padding: 2rem;
        box-shadow: 0 4px 15px rgba(0,0,0,0.1);
        margin-bottom: 2rem;
    }

    .form-section {
        margin-bottom: 2rem;
        padding-bottom: 1.5rem;
        border-bottom: 1px solid #f8f9fa;
    }

    .form-section:last-child {
        border-bottom: none;
        margin-bottom: 0;
    }

    .section-title {
        font-size: 1.25rem;
        font-weight: 600;
        color: #2c3e50;
        margin-bottom: 1.5rem;
        display: flex;
        align-items: center;
    }

    .section-title i {
        margin-right: 0.5rem;
        color: #007bff;
    }

    .form-label {
        font-weight: 600;
        color: #495057;
        margin-bottom: 0.5rem;
    }

    .form-control, .form-select {
        border-radius: 8px;
        border: 2px solid #e9ecef;
        padding: 0.75rem 1rem;
        transition: all 0.3s ease;
    }

    .form-control:focus, .form-select:focus {
        border-color: #007bff;
        box-shadow: 0 0 0 0.2rem rgba(0, 123, 255, 0.25);
    }

    .form-text {
        font-size: 0.875rem;
        color: #6c757d;
        margin-top: 0.25rem;
    }

    .photo-upload {
        position: relative;
        display: inline-block;
        cursor: pointer;
    }

    .photo-preview {
        width: 200px;
        height: 150px;
        border: 2px dashed #dee2e6;
        border-radius: 8px;
        display: flex;
        align-items: center;
        justify-content: center;
        background: #f8f9fa;
        transition: all 0.3s ease;
        position: relative;
        overflow: hidden;
    }

    .photo-preview:hover {
        border-color: #007bff;
        background: #e3f2fd;
    }

    .photo-preview img {
        width: 100%;
        height: 100%;
        object-fit: cover;
        border-radius: 6px;
    }

    .photo-placeholder {
        text-align: center;
        color: #6c757d;
    }

    .photo-placeholder i {
        font-size: 2rem;
        margin-bottom: 0.5rem;
        display: block;
    }

    .photo-upload input[type="file"] {
        position: absolute;
        opacity: 0;
        width: 100%;
        height: 100%;
        cursor: pointer;
    }

    .photo-remove {
        position: absolute;
        top: 5px;
        right: 5px;
        background: rgba(220, 53, 69, 0.8);
        color: white;
        border: none;
        border-radius: 50%;
        width: 30px;
        height: 30px;
        display: none;
        align-items: center;
        justify-content: center;
        cursor: pointer;
    }

    .photo-preview:hover .photo-remove {
        display: flex;
    }

    .current-photo {
        margin-bottom: 1rem;
    }

    .current-photo img {
        width: 200px;
        height: 150px;
        object-fit: cover;
        border-radius: 8px;
        border: 2px solid #e9ecef;
    }

    .required {
        color: #dc3545;
    }

    .form-actions {
        display: flex;
        gap: 1rem;
        justify-content: center;
        margin-top: 2rem;
        padding-top: 1.5rem;
        border-top: 1px solid #f8f9fa;
    }

    .btn-action {
        padding: 0.75rem 2rem;
        border-radius: 8px;
        font-weight: 500;
        text-decoration: none;
        transition: all 0.3s ease;
        min-width: 120px;
    }

    .btn-action:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 15px rgba(0,0,0,0.2);
    }

    .invalid-feedback {
        display: block;
        color: #dc3545;
        font-size: 0.875rem;
        margin-top: 0.25rem;
    }

    .form-check {
        margin-top: 1rem;
        padding: 1rem;
        background: #f8f9fa;
        border-radius: 8px;
    }

    .form-check-label {
        font-weight: 500;
        color: #495057;
    }

    .campus-info {
        background: #e3f2fd;
        border-left: 4px solid #007bff;
        padding: 1rem;
        border-radius: 8px;
        margin-bottom: 2rem;
    }

    .campus-info h5 {
        color: #0d47a1;
        margin-bottom: 0.5rem;
    }

    .campus-info p {
        color: #1565c0;
        margin: 0;
        font-size: 0.875rem;
    }

    @media (max-width: 768px) {
        .form-actions {
            flex-direction: column;
        }

        .btn-action {
            width: 100%;
        }

        .form-card {
            padding: 1.5rem;
        }
    }
</style>
{% endblock %}

{% block content %}
<div class="container-fluid">
    <div class="row justify-content-center">
        <div class="col-lg-8">
            <!-- 校区信息提示 -->
            <div class="campus-info">
                <h5><i class="bi bi-info-circle me-2"></i>正在编辑校区</h5>
                <p>
                    校区名称：{{ campus.name }} |
                    当前状态：{% if campus.status == 'active' %}正常运营{% else %}暂停运营{% endif %} |
                    创建时间：{{ campus.created_at.strftime('%Y年%m月%d日') if campus.created_at else '未知' }}
                </p>
            </div>

            <div class="form-card">
                <form method="POST" enctype="multipart/form-data" id="campusForm">
                    {{ form.hidden_tag() }}

                    <!-- 基本信息 -->
                    <div class="form-section">
                        <h4 class="section-title">
                            <i class="bi bi-info-circle"></i>基本信息
                        </h4>

                        <div class="row">
                            <div class="col-md-6 mb-3">
                                {{ form.name.label(class="form-label") }}
                                <span class="required">*</span>
                                {{ form.name(class="form-control") }}
                                {% if form.name.errors %}
                                    {% for error in form.name.errors %}
                                        <div class="invalid-feedback">{{ error }}</div>
                                    {% endfor %}
                                {% endif %}
                                <div class="form-text">校区的正式名称，将显示在系统各处</div>
                            </div>

                            <div class="col-md-6 mb-3">
                                {{ form.phone.label(class="form-label") }}
                                <span class="required">*</span>
                                {{ form.phone(class="form-control") }}
                                {% if form.phone.errors %}
                                    {% for error in form.phone.errors %}
                                        <div class="invalid-feedback">{{ error }}</div>
                                    {% endfor %}
                                {% endif %}
                                <div class="form-text">校区的联系电话</div>
                            </div>
                        </div>

                        <div class="mb-3">
                            {{ form.address.label(class="form-label") }}
                            <span class="required">*</span>
                            {{ form.address(class="form-control") }}
                            {% if form.address.errors %}
                                {% for error in form.address.errors %}
                                    <div class="invalid-feedback">{{ error }}</div>
                                {% endfor %}
                            {% endif %}
                            <div class="form-text">校区的详细地址</div>
                        </div>

                        <div class="row">
                            <div class="col-md-6 mb-3">
                                {{ form.email.label(class="form-label") }}
                                {{ form.email(class="form-control") }}
                                {% if form.email.errors %}
                                    {% for error in form.email.errors %}
                                        <div class="invalid-feedback">{{ error }}</div>
                                    {% endfor %}
                                {% endif %}
                                <div class="form-text">校区的邮箱地址（可选）</div>
                            </div>

                            <div class="col-md-6 mb-3">
                                {{ form.admin_id.label(class="form-label") }}
                                {{ form.admin_id(class="form-select") }}
                                {% if form.admin_id.errors %}
                                    {% for error in form.admin_id.errors %}
                                        <div class="invalid-feedback">{{ error }}</div>
                                    {% endfor %}
                                {% endif %}
                                <div class="form-text">
                                    当前管理员：
                                    {% if campus.admin %}
                                        {{ campus.admin.real_name }}
                                    {% else %}
                                        <span class="text-warning">未分配</span>
                                    {% endif %}
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- 规模信息 -->
                    <div class="form-section">
                        <h4 class="section-title">
                            <i class="bi bi-rulers"></i>规模信息
                        </h4>

                        <div class="row">
                            <div class="col-md-6 mb-3">
                                {{ form.capacity.label(class="form-label") }}
                                <span class="required">*</span>
                                <div class="input-group">
                                    {{ form.capacity(class="form-control") }}
                                    <span class="input-group-text">人</span>
                                </div>
                                {% if form.capacity.errors %}
                                    {% for error in form.capacity.errors %}
                                        <div class="invalid-feedback">{{ error }}</div>
                                    {% endfor %}
                                {% endif %}
                                <div class="form-text">校区最大容纳人数</div>
                            </div>

                            <div class="col-md-6 mb-3">
                                {{ form.area.label(class="form-label") }}
                                <div class="input-group">
                                    {{ form.area(class="form-control") }}
                                    <span class="input-group-text">m²</span>
                                </div>
                                {% if form.area.errors %}
                                    {% for error in form.area.errors %}
                                        <div class="invalid-feedback">{{ error }}</div>
                                    {% endfor %}
                                {% endif %}
                                <div class="form-text">校区场地面积（可选）</div>
                            </div>
                        </div>
                    </div>

                    <!-- 详细信息 -->
                    <div class="form-section">
                        <h4 class="section-title">
                            <i class="bi bi-card-text"></i>详细信息
                        </h4>

                        <div class="mb-3">
                            {{ form.operating_hours.label(class="form-label") }}
                            {{ form.operating_hours(class="form-control") }}
                            {% if form.operating_hours.errors %}
                                {% for error in form.operating_hours.errors %}
                                    <div class="invalid-feedback">{{ error }}</div>
                                {% endfor %}
                            {% endif %}
                            <div class="form-text">营业时间，例如：周一至周日 09:00-22:00</div>
                        </div>

                        <div class="mb-3">
                            {{ form.description.label(class="form-label") }}
                            {{ form.description(class="form-control") }}
                            {% if form.description.errors %}
                                {% for error in form.description.errors %}
                                    <div class="invalid-feedback">{{ error }}</div>
                                {% endfor %}
                            {% endif %}
                            <div class="form-text">校区的描述信息（可选）</div>
                        </div>

                        <div class="mb-3">
                            {{ form.facilities.label(class="form-label") }}
                            {{ form.facilities(class="form-control") }}
                            {% if form.facilities.errors %}
                                {% for error in form.facilities.errors %}
                                    <div class="invalid-feedback">{{ error }}</div>
                                {% endfor %}
                            {% endif %}
                            <div class="form-text">描述校区的设施设备（可选）</div>
                        </div>
                    </div>

                    <!-- 校区照片 -->
                    <div class="form-section">
                        <h4 class="section-title">
                            <i class="bi bi-camera"></i>校区照片
                        </h4>

                        {% if campus.photo_url %}
                        <div class="current-photo">
                            <label class="form-label">当前照片</label>
                            <div>
                                <img src="{{ campus.photo_url }}" alt="{{ campus.name }}" class="current-photo">
                            </div>
                            <div class="form-text">当前校区照片，上传新照片将替换此图片</div>
                        </div>
                        {% endif %}

                        <div class="mb-3">
                            {{ form.photo.label(class="form-label") }}
                            <div class="photo-upload">
                                <div class="photo-preview" id="photoPreview">
                                    <div class="photo-placeholder">
                                        <i class="bi bi-camera"></i>
                                        <div>点击上传新照片</div>
                                        <small>支持 JPG、PNG、GIF 格式</small>
                                    </div>
                                    {{ form.photo() }}
                                    <button type="button" class="photo-remove" onclick="removePhoto()">
                                        <i class="bi bi-x"></i>
                                    </button>
                                </div>
                            </div>
                            {% if form.photo.errors %}
                                {% for error in form.photo.errors %}
                                    <div class="invalid-feedback">{{ error }}</div>
                                {% endfor %}
                            {% endif %}
                            <div class="form-text">上传新照片将替换当前照片，建议尺寸 800x600 像素</div>
                        </div>
                    </div>

                    <!-- 状态设置 -->
                    <div class="form-section">
                        <h4 class="section-title">
                            <i class="bi bi-toggle-on"></i>状态设置
                        </h4>

                        <div class="form-check">
                            {{ form.is_active(class="form-check-input") }}
                            {{ form.is_active.label(class="form-check-label") }}
                            <div class="form-text">
                                当前状态：
                                {% if campus.status == 'active' %}
                                    <span class="text-success">正常运营</span>
                                {% else %}
                                    <span class="text-warning">暂停运营</span>
                                {% endif %}
                                。启用后校区将立即可用，禁用后将暂停运营
                            </div>
                        </div>
                    </div>

                    <!-- 操作按钮 -->
                    <div class="form-actions">
                        <a href="{{ url_for('campus.detail', id=campus.id) }}" class="btn btn-secondary btn-action">
                            <i class="bi bi-arrow-left me-2"></i>取消
                        </a>
                        <button type="submit" class="btn btn-warning btn-action">
                            <i class="bi bi-check-circle me-2"></i>保存修改
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const photoInput = document.querySelector('input[type="file"]');
    const photoPreview = document.getElementById('photoPreview');

    // 照片预览功能
    photoInput.addEventListener('change', function(e) {
        const file = e.target.files[0];
        if (file) {
            // 验证文件类型
            const validTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif'];
            if (!validTypes.includes(file.type)) {
                alert('请选择有效的图片文件（JPG、PNG、GIF）');
                e.target.value = '';
                return;
            }

            // 验证文件大小（5MB）
            const maxSize = 5 * 1024 * 1024;
            if (file.size > maxSize) {
                alert('图片文件大小不能超过5MB');
                e.target.value = '';
                return;
            }

            // 显示预览
            const reader = new FileReader();
            reader.onload = function(e) {
                photoPreview.innerHTML = `
                    <img src="${e.target.result}" alt="新照片预览">
                    <input type="file" name="photo" accept="image/*">
                    <button type="button" class="photo-remove" onclick="removePhoto()">
                        <i class="bi bi-x"></i>
                    </button>
                `;
            };
            reader.readAsDataURL(file);
        }
    });

    // 表单验证
    const form = document.getElementById('campusForm');
    form.addEventListener('submit', function(e) {
        let isValid = true;

        // 验证必填字段
        const requiredFields = ['name', 'address', 'phone', 'capacity'];
        requiredFields.forEach(fieldName => {
            const field = form.querySelector(`[name="${fieldName}"]`);
            if (!field.value.trim()) {
                isValid = false;
                field.classList.add('is-invalid');
            } else {
                field.classList.remove('is-invalid');
            }
        });

        // 验证电话号码格式
        const phoneField = form.querySelector('[name="phone"]');
        const phonePattern = /^1[3-9]\d{9}$|^0\d{2,3}-?\d{7,8}$/;
        if (phoneField.value && !phonePattern.test(phoneField.value)) {
            isValid = false;
            phoneField.classList.add('is-invalid');
        } else {
            phoneField.classList.remove('is-invalid');
        }

        // 验证邮箱格式
        const emailField = form.querySelector('[name="email"]');
        const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        if (emailField.value && !emailPattern.test(emailField.value)) {
            isValid = false;
            emailField.classList.add('is-invalid');
        } else {
            emailField.classList.remove('is-invalid');
        }

        if (!isValid) {
            e.preventDefault();
            alert('请检查表单中的错误信息');
            return false;
        }

        // 显示提交中状态
        const submitBtn = form.querySelector('button[type="submit"]');
        submitBtn.disabled = true;
        submitBtn.innerHTML = '<i class="bi bi-hourglass-split me-2"></i>保存中...';
    });
});

// 移除照片预览
function removePhoto() {
    const photoPreview = document.getElementById('photoPreview');
    photoPreview.innerHTML = `
        <div class="photo-placeholder">
            <i class="bi bi-camera"></i>
            <div>点击上传新照片</div>
            <small>支持 JPG、PNG、GIF 格式</small>
        </div>
        <input type="file" name="photo" accept="image/*">
        <button type="button" class="photo-remove" onclick="removePhoto()">
            <i class="bi bi-x"></i>
        </button>
    `;

    // 重新绑定事件
    const photoInput = photoPreview.querySelector('input[type="file"]');
    photoInput.addEventListener('change', function(e) {
        // 重新绑定change事件逻辑
        location.reload(); // 简单处理，重新加载页面
    });
}
</script>
{% endblock %}